package server

import (
	"errors"
	"gedis/protocol/codec"
)

const (
	PUT = iota + 1
	GET
	DEL
)

const EmptyString = ""

var CommandTable = map[int8]ICommandExecutor{
	PUT: &PutCommandExecutor{},
	GET: &GetCommandExecutor{},
	DEL: &DelCommandExecutor{},
}

// ICommandExecutor is command executor interface.
type ICommandExecutor interface {
	// Process the command.
	Process(request *codec.RequestProtocol, gs *GedisServer) (data string, err error)
}

// PutCommandExecutor is put command executor.
type PutCommandExecutor struct{}

func (executor *PutCommandExecutor) Process(request *codec.RequestProtocol, gs *GedisServer) (data string, err error) {
	if len(request.Args) != 2 {
		return EmptyString, errors.New("put command args count not equals 2")
	}
	gs.DB.Put(request.Args[0], request.Args[1])
	return EmptyString, nil
}

// GetCommandExecutor is get command executor.
type GetCommandExecutor struct{}

func (executor *GetCommandExecutor) Process(request *codec.RequestProtocol, gs *GedisServer) (data string, err error) {
	if len(request.Args) != 1 {
		return EmptyString, errors.New("get command args count not equals 1")
	}
	return gs.DB.Get(request.Args[0]), nil
}

// DelCommandExecutor is del command executor.
type DelCommandExecutor struct{}

func (executor *DelCommandExecutor) Process(request *codec.RequestProtocol, gs *GedisServer) (data string, err error) {
	if len(request.Args) != 1 {
		return EmptyString, errors.New("del command args count not equals 1")
	}
	gs.DB.Del(request.Args[0])
	return EmptyString, nil
}
